<template>
  <view class="content">
    <Tooltip class="tooltip" :tipTxt="state.tipTxt"></Tooltip>
    <image
      class="btn-img"
      mode="aspectFill"
      src="../../static/icon-end.png"
      @longpress="onTouchStart"
      @touchend="onTouchEnd"
    ></image>
    <!-- <view class="bg-circle" v-if="state.longEnd"></view> -->
    <canvas canvas-id="circleCanvas" class="canvas-circle" v-if="state.longEnd"></canvas>
    <canvas canvas-id="circleCanvasBg" class="canvas-circle" v-if="state.longEnd"></canvas>
  </view>
</template>

<script setup lang="ts">
import { onLaunch, onShow, onHide, onUnload } from "@dcloudio/uni-app";
import { reactive, ref, toRefs, watch, onMounted, getCurrentInstance, defineEmits } from "vue"
import Tooltip from "./tooltip"
import { storeToRefs } from "pinia";
import { useRunInfoStore } from "../../store/runInfo";
import { useChatStore } from "../../store/chat"
const useChatData = useChatStore()
const useRunInfoData = useRunInfoStore()
const instance = getCurrentInstance() as any
const { sseEnd } = storeToRefs(useChatData)
const { runUuid, runType, runMileage, matchSpeed, totalSeconds } = storeToRefs(useRunInfoData)
const emit = defineEmits(['endRecord', "onTouchEndCb"])
const state = reactive({
  tipTxt: "长按结束",
  longEnd: false,
  circleEnd: false,
  interval: null,
  ctx: null,
  progress: 0, // 进度条的当前进度
  animation: null // 动画实例
})

const onTouchStart = () => {
  // if (state.circleEnd) return
  state.longEnd = true;
  drawCircle()
  startProgressAnimation();
  let params = {
    timeType: 2, 
    uuid: runUuid.value,
    duration: totalSeconds.value,
    distance: runMileage.value,
    pace: matchSpeed.value
  }
  useChatData.setAllContent("")
  useChatData.getRobotMsg(params)
};

const onTouchEnd = () => {
  state.longEnd = false;
  state.progress = 0
  clearInterval(state.interval);
};

const drawCircle = (type) => {
  console.log("绘制")
  const ctx = uni.createCanvasContext('circleCanvasBg', instance);
  // 绘制圆形背景
  ctx.beginPath();
  // this.ctx.arc(100, 100, 50, 0, 2 * Math.PI);
  ctx.arc(35.7, 35.7, 33, 0, 2 * Math.PI);
  ctx.setLineWidth(3);
  ctx.setStrokeStyle('rgba(0,0,0,0.1)');
  ctx.stroke();
  ctx.draw();
}
const startProgressAnimation = () => {
  const duration = 1500; // 动画持续时间（毫秒）
  state.animation = uni.createAnimation({
    duration: duration,
    timingFunction: 'linear',
    delay: 0
  });
  const step = () => {
    state.progress += 1;
    if (state.progress > 100) {
      state.progress = 100;
      clearInterval(state.interval);
      state.circleEnd = true
      useRunInfoData.endTask("end");
      useRunInfoData.setIsRuning(false)
      return;
    }
    drawProgress(state.progress);
  };
  state.interval = setInterval(step, duration / 100);
}
const drawProgress = (progress) => {
  const ctx = uni.createCanvasContext('circleCanvas', instance);
  // 清除之前的绘制内容
  // ctx.clearRect(0, 0, 200, 200);
  // // 重新绘制背景圆形
  // drawCircle();
  // 绘制进度圆弧
  ctx.beginPath();
  ctx.arc(35.7, 35.7, 33, -0.5 * Math.PI, ((2 * Math.PI) / 100) * progress - 0.5 * Math.PI);
  ctx.setLineWidth(3);
  ctx.setStrokeStyle('rgba(255,255,255,1)');
  // ctx.setStrokeStyle('rgba(0,0,0,0)');
  ctx.stroke();
  ctx.draw();
}

const upDateImgCb = () => {
  setTimeout(() => {
    state.circleEnd = false
    state.longEnd = false;
  }, 2500);
}

watch(
  [() => sseEnd.value, () => state.circleEnd],
  ([newPropA, newPropB], [oldPropA, oldPropB]) => {
    console.log("newPropA", newPropA, newPropB)
    if (newPropA && newPropB) {
      let runMileage = useRunInfoData.runMileage
      let totalSeconds = useRunInfoData.totalSeconds
      useRunInfoData.onEndMileage(totalSeconds, runMileage).then(res => {
        console.log("结束运动")
        emit("onTouchEndCb", state.circleEnd)
        emit('endRecord', true);
      }).catch(err => {
        state.circleEnd = false
        state.longEnd = false;
      })
    }
  }
);

defineExpose({
  upDateImgCb
});

</script>

<style lang="scss" scoped>
.content {
  width: 180rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 180rpx;
  position: relative;
}
.btn-img{
  width: 180rpx;
  height: 180rpx;
  position: relative;
}
.bg-circle{
  width: 120rpx;
  height: 120rpx;
  border-radius: 100%;
  border: 6rpx solid rgba(0,0,0,0.2);
  position: absolute;
  left: 50%;
  top:50%;
  transform: translate(-50%, -50%);
}
.canvas-circle{
  width: 140rpx;
  height: 140rpx;
  position: absolute;
  left: 50%;
  top: 50%;
  z-index:999;
  transform: translate(-50%, -50%);
}
.tooltip{
  position: absolute;
  left: 27rpx;
  top: -100rpx;
}
</style>
